package com.ouken.com;

import com.gen.tool.AlertDialog_ok;
import com.gen.tool.AlertDialog_ok_cancel;
import com.gen.tool.AlertDialog_password;
import com.gen.tool.SoundPlayer;
import com.ouken.asynTask.AsynEnterRoom;
import com.ouken.asynTask.AsynRefreshRoomlist;
import com.ouken.service.RefreshRoomlistService;
//import com.ouken.tool.MplayerTool;
import com.ouken.tool.MyApp;
import com.ouken.tool.RoomlistAdapter;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.os.IBinder;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class RoomlistActivity extends Activity {
	
	 
	private String[] contents = {"OK","OK"};
	private MyApp appState;
	private SharedPreferences userInfo;
	private ListView roomlistView;
	private ImageButton ib_createroom;
	private	ImageButton ib_back;
	//private MplayerTool mplayerTool ;
	private Context context;
	private UpdateReceiver roomlistUpdateReceiver;
	private EditText searchRoomname;
	private ImageButton search;
	private ImageButton reset;
	private	RelativeLayout RL_bg ;
	private RefreshRoomlistService refreshRoomlistService = null;
	private IntentFilter filter;
	private ServiceConnection connection = new ServiceConnection(){

		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			refreshRoomlistService = ((RefreshRoomlistService.LocalBinder) service).getService();
		}

		@Override
		public void onServiceDisconnected(ComponentName name) {
			refreshRoomlistService = null;
		}
		
	};
	private Intent intentToSerice;
		
	private void initView(){
			userInfo  = getSharedPreferences("user_info", 0);
			appState = ((MyApp)getApplicationContext());
			//appState.setMusic(userInfo.getString("MUSIC", "ON").equals("ON"));
			appState.addActivity(RoomlistActivity.this);
			
			ib_createroom = (ImageButton)findViewById(R.id.roomlistActivity_ib_createroom);
			ib_back = (ImageButton)findViewById(R.id.roomlistActivity_ib_back);
			roomlistView = (ListView)findViewById(R.id.roomlistActivity_lv_roomlistView);
			//mplayerTool = new MplayerTool(RoomlistActivity.this);
			searchRoomname = (EditText)findViewById(R.id.roomlistActivity_et_search_roomname);
			search = (ImageButton)findViewById(R.id.roomlistActivity_ib_search);
			reset =(ImageButton)findViewById(R.id.roomlistActivity_ib_reset);
			context = RoomlistActivity.this;
			RL_bg = (RelativeLayout)findViewById(R.id.relativeLayout_roomlist_bg);
			
		
	        
	        
	        
			//Bundle extras = getIntent().getExtras(); 
			//if(extras!=null) contents = extras.getString("result").split(",");
			
			Bundle bundle  = new Bundle();
	        bundle.putString("roomname","" );
	        
	        //intentToSerice = new Intent("com.serive.refreshroomlist");
	        
	        intentToSerice = new Intent(this,RefreshRoomlistService.class);
	        intentToSerice.putExtras(bundle);
			
			roomlistUpdateReceiver = new UpdateReceiver();
	        filter= new IntentFilter();
	        filter.addAction("com.updataReceiver");
	        filter.addAction("open.ProcessTitleBar");
	        registerReceiver(roomlistUpdateReceiver, filter);
	        
	       // bindService(intentToSerice, connection, Context.BIND_AUTO_CREATE);
			
			//startService(intentToSerice); 
			      
			
			
	}
	 public void onCreate(Bundle savedInstanceState) {
	        super.onCreate(savedInstanceState);
	    	requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); //process title bar
	        setContentView(R.layout.roomlist);
	        initView();
	        
	        RL_bg.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					((InputMethodManager)getSystemService(INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(RoomlistActivity.this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
				}
			});
			
			ib_createroom.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					SoundPlayer.playSound(R.raw.keypress_common);
					//mplayerTool.playButtonPressed(RoomlistActivity.this);
					Intent intent = new Intent(RoomlistActivity.this,CreateroomActivity.class);
					startActivity(intent);
					
					//RoomlistActivity.this.finish();
					
				}
			});
			
			ib_back.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					SoundPlayer.playSound(R.raw.keypress_common);
					//mplayerTool.playButtonPressed(RoomlistActivity.this);
					RoomlistActivity.this.finish();
				}
			});
			
			RoomlistAdapter adapter=new RoomlistAdapter(this,contents);  
			roomlistView.setAdapter(adapter);
			roomlistView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1,
						final int arg2, long arg3) {

					RoomlistActivity.this.onPause();
					
					if(!contents[5*arg2 + 3].equals("0")){  //this room is playing and can not enter
						AlertDialog_ok alertDialog = new AlertDialog_ok(context,"Sorry, This room is playing!");
						final AlertDialog now = alertDialog.AlertDialog_ok_show();
						alertDialog.getConfirm_btn_ok().setOnClickListener(new View.OnClickListener() {
							
							@Override
							public void onClick(View v) {
								SoundPlayer.playSound(R.raw.keypress_common);
		                    	RoomlistActivity.this.onResume();
		                    	now.dismiss();
							}
						});
						 
						 return;
		            }
					
						
		                
					
					AlertDialog_ok_cancel alertDialog_ok_cancel = new AlertDialog_ok_cancel(context,"enter "+contents[5*arg2 + 2]+" ?");
					final AlertDialog now = alertDialog_ok_cancel.AlertDialog_ok_cancel_show();
					alertDialog_ok_cancel.getConfirm_btn_ok().setOnClickListener(new View.OnClickListener() {
						
						@Override
						public void onClick(View v) {
							SoundPlayer.playSound(R.raw.keypress_common);
							now.dismiss();
							if(contents[5*arg2 + 6].equals("?????????????")){
	                    		appState.setRoomName(contents[5*arg2 + 2]);
                        		appState.setMem(String.valueOf(Integer.parseInt(contents[5*arg2 + 4])+1), contents[5*arg2 + 5]);
    	                    	new AsynEnterRoom(context, appState, contents[5*arg2 + 2].toString()).execute();
	                    		return;
	                    	}
							
						   /* AlertDialog_password alertDialogPWD = new AlertDialog_password(context,"Please entry Password");
							final Dialog now = alertDialogPWD.AlertDialog_ok_cancel_show();
							final EditText et_roomPSW = alertDialogPWD.getEv_pwd();
							
							alertDialogPWD.getConfirm_btn_ok().setOnClickListener(new View.OnClickListener() {
								
								@Override
								public void onClick(View v) {
									SoundPlayer.playSound(R.raw.keypress_common);
	                            	
	                            	if(contents[5*arg2 + 6].equals("?????????????") || et_roomPSW.getText().toString().equals(contents[5*arg2 + 6])){
	                            		//Toast.makeText(RoomlistActivity.this, contents[5*arg2 + 2], Toast.LENGTH_SHORT).show();
	                            		appState.setRoomName(contents[5*arg2 + 2]);
	                            		appState.setMem(String.valueOf(Integer.parseInt(contents[5*arg2 + 4])+1), contents[5*arg2 + 5]);
	        	                    	new AsynEnterRoom(context, appState, contents[5*arg2 + 2].toString()).execute();
	                            	}
	                            	else{
	                            		Toast.makeText(RoomlistActivity.this, "password is not correct!", Toast.LENGTH_SHORT).show();
	                            		RoomlistActivity.this.onResume();
	                            	}
	                            	now.dismiss();
									
								}
							});
							
							alertDialogPWD.getCancel_btn_can().setOnClickListener(new View.OnClickListener() {
								
								@Override
								public void onClick(View v) {
									SoundPlayer.playSound(R.raw.keypress_common);
	                            	RoomlistActivity.this.onResume();
	                            	now.dismiss();
								}
							});*/
							
							LayoutInflater factory = LayoutInflater.from(context);
	                    	final View textEntryView = factory.inflate(R.layout.alert_dialog_text_entry, null);
	                        
	                    	AlertDialog passwdDialog = new AlertDialog.Builder(RoomlistActivity.this)
	                        .setIcon(R.drawable.alert_dialog_icon)
	                        .setTitle("Please entry Password")
	                        .setView(textEntryView)
	                        .setPositiveButton("Enter", new DialogInterface.OnClickListener() {
	                            public void onClick(DialogInterface dialog, int whichButton) {
	                            	SoundPlayer.playSound(R.raw.keypress_common);
	                            	EditText et_roomPSW = (EditText) textEntryView.findViewById(R.id.Password_edit);
	                            	if(contents[5*arg2 + 6].equals("?????????????") || et_roomPSW.getText().toString().equals(contents[5*arg2 + 6])){
	                            		//Toast.makeText(RoomlistActivity.this, contents[5*arg2 + 2], Toast.LENGTH_SHORT).show();
	                            		appState.setRoomName(contents[5*arg2 + 2]);
	                            		appState.setMem(String.valueOf(Integer.parseInt(contents[5*arg2 + 4])+1), contents[5*arg2 + 5]);
	        	                    	new AsynEnterRoom(context, appState, contents[5*arg2 + 2].toString()).execute();
	                            	}
	                            	else{
	                            		//Toast.makeText(RoomlistActivity.this, "password is not correct!", Toast.LENGTH_SHORT).show();
	                            		RoomlistActivity.this.onResume();
	                            	}
	                            	
	                            }
	                        })
	                        .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
	                            public void onClick(DialogInterface dialog, int whichButton) {
	                            	SoundPlayer.playSound(R.raw.keypress_common);
	                            	RoomlistActivity.this.onResume();
	                            }
	                        })
	                        .create();
	                    	
	                    	passwdDialog.show();
							
							
						}
					});
					alertDialog_ok_cancel.getCancel_btn_can().setOnClickListener(new View.OnClickListener() {
						
						@Override
						public void onClick(View v) {
							SoundPlayer.playSound(R.raw.keypress_common);
                        	RoomlistActivity.this.onResume();
                        	now.dismiss();
                        	
						}
					});
					
					/*AlertDialog alertDialog =
					new AlertDialog.Builder(RoomlistActivity.this)
	                .setIcon(R.drawable.alert_dialog_icon)
	                .setTitle("enter "+contents[5*arg2 + 2]+" ?")
	                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
	                    public void onClick(DialogInterface dialog, int whichButton) {
	                    	SoundPlayer.playSound(R.raw.keypress_common);
	                    	//Toast.makeText(RoomlistActivity.this, contents[5*arg2 + 2], Toast.LENGTH_SHORT).show();
	                    	dialog.dismiss();
	                    	
	                    	
	                    	if(contents[5*arg2 + 6].equals("?????????????")){
	                    		appState.setRoomName(contents[5*arg2 + 2]);
                        		appState.setMem(String.valueOf(Integer.parseInt(contents[5*arg2 + 4])+1), contents[5*arg2 + 5]);
    	                    	new AsynEnterRoom(context, appState, contents[5*arg2 + 2].toString()).execute();
	                    		return;
	                    	}
	                    	
	                    	LayoutInflater factory = LayoutInflater.from(context);
	                    	final View textEntryView = factory.inflate(R.layout.alert_dialog_text_entry, null);
	                        
	                    	AlertDialog passwdDialog = new AlertDialog.Builder(RoomlistActivity.this)
	                        .setIcon(R.drawable.alert_dialog_icon)
	                        .setTitle("Please entry Password")
	                        .setView(textEntryView)
	                        .setPositiveButton("Enter", new DialogInterface.OnClickListener() {
	                            public void onClick(DialogInterface dialog, int whichButton) {
	                            	SoundPlayer.playSound(R.raw.keypress_common);
	                            	EditText et_roomPSW = (EditText) textEntryView.findViewById(R.id.Password_edit);
	                            	if(contents[5*arg2 + 6].equals("?????????????") || et_roomPSW.getText().toString().equals(contents[5*arg2 + 6])){
	                            		//Toast.makeText(RoomlistActivity.this, contents[5*arg2 + 2], Toast.LENGTH_SHORT).show();
	                            		appState.setRoomName(contents[5*arg2 + 2]);
	                            		appState.setMem(String.valueOf(Integer.parseInt(contents[5*arg2 + 4])+1), contents[5*arg2 + 5]);
	        	                    	new AsynEnterRoom(context, appState, contents[5*arg2 + 2].toString()).execute();
	                            	}
	                            	else{
	                            		//Toast.makeText(RoomlistActivity.this, "password is not correct!", Toast.LENGTH_SHORT).show();
	                            		RoomlistActivity.this.onResume();
	                            	}
	                            	
	                            }
	                        })
	                        .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
	                            public void onClick(DialogInterface dialog, int whichButton) {
	                            	SoundPlayer.playSound(R.raw.keypress_common);
	                            	RoomlistActivity.this.onResume();
	                            }
	                        })
	                        .create();
	                    	
	                    	passwdDialog.show();
	                    	
	                    	
	                    }
	                })
	                .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
	                    public void onClick(DialogInterface dialog, int whichButton) {
	                    	SoundPlayer.playSound(R.raw.keypress_common);
	                    	RoomlistActivity.this.onResume();
	                    }
	                })
	                .create();
				
					alertDialog.show();*/
				
				
				}
			});
			search.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					SoundPlayer.playSound(R.raw.keypress_common);
					//mplayerTool.playButtonPressed(RoomlistActivity.this);
					try{
						unbindService(connection);
						}
						catch(Exception e){
							
						}
						System.out.println("RoomListRefresh service in search unbinded");
					new AsynRefreshRoomlist(context, appState, searchRoomname.getText().toString(), roomlistView).execute();
				}
			});
			
			reset.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					SoundPlayer.playSound(R.raw.keypress_common);
					//mplayerTool.playButtonPressed(RoomlistActivity.this);
					bindService(intentToSerice, connection, Context.BIND_AUTO_CREATE);
					System.out.println("RoomListRefresh service in search binded");
				}
			});
	 }
	 
	 
	 
	 @Override
	protected void onResume() {
		super.onResume();
		bindService(intentToSerice, connection, Context.BIND_AUTO_CREATE);
		System.out.println("Activity onResume");

	}
	@Override
	protected void onPause() {
		super.onPause();
		try{
		unbindService(connection);
		}
		catch(Exception e){
			
		}
		System.out.println("Activity onPause");

	}
	
	
	@Override
	protected void onDestroy() {
		 super.onDestroy();
		 unregisterReceiver(roomlistUpdateReceiver);
		 
		 System.out.println("Activity onDestroy");
	
	}



	public class UpdateReceiver extends BroadcastReceiver{
		    

			@Override
			public void onReceive(Context arg0, Intent arg1) {
				String action = arg1.getAction();
				String result;
				if(action.equals("com.updataReceiver")){
					
					System.out.println("Enter Roomlist updataReceiver");
					Bundle bundle = arg1.getExtras();
					if(bundle !=null){
						result = bundle.getString("result");
						if(result == null) return;
						//Toast.makeText(context, result, Toast.LENGTH_LONG).show();
						result = result.replaceAll("(\\ )", "");
						contents = result.split(",");
						RoomlistAdapter adapter=new RoomlistAdapter(context,contents);  
						roomlistView.setAdapter(adapter);
						System.out.println("Roomlist updata");
						setProgressBarIndeterminateVisibility(false);
					}
					
					
				}
				else if(action.equals("open.ProcessTitleBar")){
					setProgressBarIndeterminateVisibility(true);
					System.out.println("open ProcessTitleBar");
				}
				
			}
	    }
}
